package com.gua.user.service.impl;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.gua.common.exception.BusinessExecption;
import com.gua.user.request.UserLoginParamVO;
import com.gua.user.response.LoginResultRespVO;
import com.gua.user.response.LoginUser;
import com.gua.user.response.UserInfoDetailRespVO;
import com.gua.user.service.LoginService;
import com.gua.user.utils.JwtUtil;
import com.gua.user.utils.RedisCache;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private RedisCache redisCache;

    @Override
    public LoginResultRespVO login(UserLoginParamVO userLoginParamVO) {
    	try {
	        //1. AuthenticationManager authenticate进行用户认证
	        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userLoginParamVO.getUserName(), 
	        		userLoginParamVO.getPassword());
	        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
	        //如果返回结果为null，则认证未通过，给出提示
	        if(Objects.isNull(authenticate)){
	            throw new RuntimeException("用户名或密码错误");
	        }
	        //使用userid生成token
	        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
	        String userId = loginUser.getUser().getId().toString();
	        String jwt = JwtUtil.createJWT(userId);
	        //authenticate存入redis
	        redisCache.setCacheObject("login:" + userId, loginUser);
	        LoginResultRespVO loginResultRespVO = new LoginResultRespVO();
	        //把token响应给前端
	        loginResultRespVO.setToken(jwt);
	        loginResultRespVO.setAvatar(loginUser.getUser().getAvatar());
	        loginResultRespVO.setUserName(loginUser.getUser().getUserName());
	        loginResultRespVO.setNickName(loginUser.getUser().getNickName());
	        return loginResultRespVO;
    	}catch (Exception e) {
			log.error("login", e);
			throw new BusinessExecption("用户名或者密码不正确");
		}
    }

    @Override
    public void logout() {
        //获取SecurityContextHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        //删除redis中的value
        redisCache.deleteObject("login:"+userid);
    }
    
    @Override
    public UserInfoDetailRespVO getLoginUserInfo() {
    	LoginUser loginUser = (LoginUser)SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
    	UserInfoDetailRespVO userInfoDetailRespVO = new UserInfoDetailRespVO();
    	userInfoDetailRespVO.setAvatar(loginUser.getUser().getAvatar());
    	userInfoDetailRespVO.setUserName(loginUser.getUser().getUserName());
    	userInfoDetailRespVO.setIntroduction(null);
    	userInfoDetailRespVO.setNickName(loginUser.getUser().getNickName());
    	userInfoDetailRespVO.setRoles(loginUser.getRoleKeys());
    	return userInfoDetailRespVO;
    }
}